# -*- coding: utf-8 -*-
import json
import os
import subprocess
import sys
from datetime import datetime
from tkinter import *
from tkinter import messagebox, scrolledtext
from tkinter import ttk
import pandas as pd
import requests

# ===========================================================================================
color = 0
zyl = [1.02, 1.04, 1.06]
jcd = 0.05
dt_sell_fe = []
dt_sy = []
gzf = []
gz = []  # 保存估值
gz_time = []  # 保存获取估值的时间(目前用不到)
listJZ = []  # 保存某基金的所有的历史净值
yes_jz = []  # 保存某基金最近更新的历史净值
yes_time = []  # 保存某基金最近更新的历史净值的时间
# 相关文件路径===========================================
all_xlsx_path = [r'../Fund_form_files\JJ_dt.xlsx',
                 r'../Fund_form_files/JJ_bd.xlsx',
                 r'../Fund_form_files/JJ_all.xlsx']
jj_bd = pd.read_excel(all_xlsx_path[1], dtype={'基金代码': str, '数据获取时间': str, '更新时间': str})
jj_all = pd.read_excel(all_xlsx_path[2], dtype={'基金代码': str})


# 重启程序 =============================================
def restart_tkinter():
    """完全重启Tkinter应用程序"""
    subprocess.Popen([sys.executable, os.path.abspath(sys.argv[0])])
    sys.exit(0)  # 退出当前进程


def get_gz_history(to, fund_code):
    if to == 1:  #
        url = f"http://fundgz.1234567.com.cn/js/{fund_code}.js?rt={int(datetime.now().timestamp())}"
        headers = {'Referer': 'http://fund.eastmoney.com/', 'User-Agent': 'Mozilla/5.0'}
        try:
            response = requests.get(url, headers=headers, timeout=20)
            data = json.loads(response.text.replace("jsonpgz(", "").replace(");", ""))
            gz_time.append({data['gztime']})  # 保存获取的估值时间
            gz.append(float(data['gsz']))  # 保存获取的估值
            gzf.append(data['gszzl'])
        except Exception as e:
            messagebox.showinfo('提醒', f"获取基金估算净值失败: {str(e)}")
    elif to == 2:  # 获取历史净值
        url = f"http://api.fund.eastmoney.com/f10/lsjz?fundCode={fund_code}&pageIndex=1&pageSize=20"
        headers = {
            'Referer': 'http://fundf10.eastmoney.com',
            'User-Agent': 'Mozilla/5.0'
        }
        try:
            r = requests.get(url, headers=headers, timeout=20)
            data = r.json()['Data']['LSJZList']
            for get_ls_num in range(len(data)):
                listJZ.append(float(data[get_ls_num]['DWJZ']))  # 保存所有历史净值
            yes_jz.append(float(data[0]['DWJZ']))  # 保存最近更新的历史净值
            yes_time.append(data[0]['FSRQ'])  # 保存最近更新的历史净值的时间
        except Exception as e:
            messagebox.showinfo('提醒', f"数据获取失败: {e}")
    return None

# 标准持有--买入操作函数
def shop_jj():
    jj_names = combobox.get()
    if jj_names == '':
        messagebox.showerror('错误', '基金名称为空')
    else:
        if jj_bd[jj_bd['基金名称'] == jj_names].empty:
            messagebox.showerror('错误', '你未持有该基金')
        elif combobox2.get() == '':
            messagebox.showerror('错误', '买入金额为空')
        elif combobox3.get() != '':
            messagebox.showerror('错误', '买入命令执行错误:卖出金额不为空')
        else:
            shop_money = float(combobox2.get())
            fund = jj_bd[jj_bd['基金名称'] == jj_names]['基金代码'].iloc[0]
            get_gz_history(2, fund)
            yes_fe = jj_bd[jj_bd['基金名称'] == jj_names]['持有份额'].iloc[0]  # 原持有份额
            yes_ben = jj_bd[jj_bd['基金名称'] == jj_names]['平均成本'].iloc[0]  # 原平均成本
            # shop_money_num = jj_bd[jj_bd['基金名称'] == jj_names]['补仓次数'].iloc[0]  # 原补仓次数
            ben_money = yes_ben * yes_fe  # 原来持有总金额
            add_ben_money = ben_money + shop_money  # 买入后的持有总金额
            new_shop_fe = shop_money / yes_jz[0]  # 买入的份额
            new_fe = yes_fe + new_shop_fe  # 买入后的持有总份额
            new_jun_ben = f'{add_ben_money / new_fe:.4f}'  # 买入后的平均成本
            y_or_n = messagebox.askyesno('买入信息确认',
                                         f'{jj_names}\n'
                                         f'买入金额={shop_money}\n买入净值={yes_jz[0]}\n'f'买入份额={new_shop_fe:.2f}\n'
                                         f'前平均成本={yes_ben}\n前持有份额={yes_fe}\n'
                                         f'买后平均成本={new_jun_ben}\n买后持有份额={new_fe:.2f}\n数据获取时间:{yes_time[0]}')
            if y_or_n:
                jj_bd.loc[
                    jj_bd['基金代码'] == fund, ['平均成本', '持有份额', '数据获取时间', '更新时间']] = [
                    float(new_jun_ben), float(f'{new_fe:.2f}'), yes_time[0],
                    datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')]
                jj_bd.to_excel(all_xlsx_path[1], index=False)
                messagebox.showinfo('成功', f'基金{jj_names}买入成功\n表格已更新')
    combobox0.set('未持有基金的添加(建议最后操作)')
    combobox.set('')
    combobox2.set('')
    combobox3.set('')
    yes_jz.clear()
    yes_time.clear()


# 标准持有--卖出操作函数
def sell_jj():
    jj_names = combobox.get()
    if jj_names == '':
        messagebox.showerror('错误', '基金名称为空')
    else:
        if jj_bd[jj_bd['基金名称'] == jj_names].empty:
            messagebox.showerror('错误', '你未持有该基金')
        elif combobox3.get() == '':
            messagebox.showerror('错误', '卖出份额为空')
        elif combobox2.get() != '':
            messagebox.showerror('错误', '卖出命令执行错误\n买入金额不为空')
        else:
            if combobox3.get() == '清仓':
                y_or_n = messagebox.askyesno('卖出信息确认', f'{jj_names}\n确认清仓???')
                if y_or_n:
                    jj_bd.drop(jj_bd[jj_bd['基金名称'] == jj_names].index, inplace=True)
                    jj_bd.reset_index(drop=True, inplace=True)
                    jj_bd.to_excel(all_xlsx_path[1], index=False)
                    messagebox.showinfo('成功', f'基金{jj_names}已清仓\n表格已删除对应数据')
            else:
                sell_fe_er = float(combobox3.get())
                fund = jj_bd[jj_bd['基金名称'] == jj_names]['基金代码'].iloc[0]
                get_gz_history(2, fund)
                yes_fe = jj_bd[jj_bd['基金名称'] == jj_names]['持有份额'].iloc[0]  # 原持有份额
                new_fe = yes_fe - sell_fe_er
                y_or_n = messagebox.askyesno('卖出信息确认',
                                             f'{jj_names}\n卖出份额={yes_fe * sell_fe_er:.2f}\n'
                                             f'前持有份额={yes_fe}\n买后持有份额={new_fe:.2f}\n'
                                             f'数据获取时间:{yes_time[0]}')
                if y_or_n:
                    jj_bd.loc[jj_bd['基金代码'] == fund, ['持有份额', '数据获取时间', '更新时间']] = \
                        [float(f'{yes_fe - sell_fe_er:.2f}'), yes_time[0],
                         datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')]
                    jj_bd.to_excel(all_xlsx_path[1], index=False)
                    messagebox.showinfo('成功', f'基金{jj_names}已卖出{sell_fe_er}份\n表格数据已更新')
    combobox0.set('未持有基金的添加(建议最后操作)')
    combobox.set('')
    combobox2.set('')
    combobox3.set('')
    yes_jz.clear()
    yes_time.clear()


# bug--添加新基金和买入卖出操作不可同时实现,需重启(已加执行此操作后强制重启代码)
def new_jj():
    new_jj_name = combobox0.get()
    if new_jj_name == '' or jj_all[jj_all['基金名称'] == new_jj_name].empty:
        messagebox.showerror('错误', '添加新基命令错误\n原因:添加的基金名称为空')
    elif new_jj_name in jj_bd['基金名称'].values:
        messagebox.showerror('错误', '添加新基命令错误\n原因:你已持有该基金')
    elif combobox2.get() == '':
        messagebox.showerror('错误', '添加新基命令错误\n原因:买入金额为空')
    elif combobox3.get() != '':
        messagebox.showerror('错误', '添加新基命令错误\n原因:卖出份额不为空')
    else:
        shop_mon = int(combobox2.get())
        new_jj_num = jj_all[jj_all['基金名称'] == new_jj_name]['基金代码'].iloc[0]
        get_gz_history(2, new_jj_num)
        y_or_n = messagebox.askyesno('买入新基金信息确认',
                                     f'{new_jj_name}({new_jj_num})\n买入金额:{shop_mon}\n'
                                     f'买入净值(即平均成本):{yes_jz[0]}\n买入份额(即持有份额):{shop_mon / yes_jz[0]:.2f}\n数据获取时间:{yes_time[0]}')
        if y_or_n:
            new_jj_mmr = pd.read_excel(all_xlsx_path[1],
                                       dtype={'基金代码': str})
            new_row = {'基金代码': new_jj_num, '基金名称': new_jj_name,
                       '持有份额': float(f'{shop_mon / yes_jz[0]:.2f}'), '平均成本': yes_jz[0],
                       '数据获取时间': yes_time[0],
                       '更新时间': datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')}
            add_new_j = pd.concat([new_jj_mmr, pd.DataFrame([new_row])], ignore_index=True)
            add_new_j.to_excel(all_xlsx_path[1], index=False)
            messagebox.showwarning('警告', '添加成功,关闭窗口后重启获取新数据')
            restart_tkinter()
    yes_jz.clear()
    yes_time.clear()


if __name__ == '__main__':
    # 子窗口2--标准持有基金操作页面========================================================================================
    root3 = Tk()
    root3.attributes('-topmost', True)
    root3.geometry(f"320x200+800+300")
    root3.configure(bg="lightblue")
    Label(root3, text='新基金名:', font=("Microsoft JhengHei UI", 12, "bold"),
          width=8, background="lightblue").place(x=0, y=10)
    all_num_options = []
    for a in range(len(jj_all['基金代码'])):
        all_num_options.append(jj_all['基金名称'][a])
    combobox0 = ttk.Combobox(root3, values=all_num_options, width=25)
    combobox0.set('未持有基金的添加(建议最后操作)')
    combobox0.place(x=82, y=12)
    Label(root3, text='基金名称:', font=("Microsoft JhengHei UI", 12, "bold"),
          width=8, background="lightblue").place(x=0, y=10 + 30)
    options = []
    for b in range(len(jj_bd['基金代码'])):
        options.append(jj_bd['基金名称'][b])
    combobox = ttk.Combobox(root3, values=options, width=25)
    combobox.set('')
    combobox.place(x=82, y=12 + 30)
    Label(root3, text='买入金额:', font=("Microsoft JhengHei UI", 12, "bold"),
          width=8, background="lightblue").place(x=0, y=10 + 60)
    options2 = ["", "500", '250', '125', '62.5', '31.25']
    combobox2 = ttk.Combobox(root3, values=options2, width=25)
    combobox2.set('')
    combobox2.place(x=82, y=12 + 60)
    Label(root3, text='卖出份额:', font=("Microsoft JhengHei UI", 12, "bold"),
          width=8, background="lightblue").place(x=0, y=10 + 90)
    options3 = ['', '清仓']
    combobox3 = ttk.Combobox(root3, values=options3, width=25)
    combobox3.set('')
    combobox3.place(x=82, y=12 + 90)
    shop_btn = Button(root3, text="SHOP", command=shop_jj, width=4, height=1, bg="#fed6b8", font=("黑体", 11, "bold"),
                      fg='#07aa7c', bd=6, relief="raised")
    shop_btn.place(x=20 + 10, y=150)
    new_btn = Button(root3, text="NEW", command=new_jj, width=4, height=1, bg="#fed6b8", font=("黑体", 11, "bold"),
                     fg='#ef9b00', bd=6, relief="raised")
    new_btn.place(x=20 + 100 + 10, y=150)
    sell_btn = Button(root3, text="SELL", command=sell_jj, width=4, height=1, bg="#fed6b8", font=("黑体", 11, "bold"),
                      fg='#a42127', bd=6, relief="raised")
    sell_btn.place(x=220 + 10, y=150)
    shop_btn.bind("<Enter>", lambda e, bba=shop_btn: bba.config(bg='#000000'))
    shop_btn.bind("<Leave>", lambda e, bba=shop_btn: bba.config(bg="#fed6b8"))
    new_btn.bind("<Enter>", lambda e, bba=new_btn: bba.config(bg='#000000'))
    new_btn.bind("<Leave>", lambda e, bba=new_btn: bba.config(bg="#fed6b8"))
    sell_btn.bind("<Enter>", lambda e, bba=sell_btn: bba.config(bg='#000000'))
    sell_btn.bind("<Leave>", lambda e, bba=sell_btn: bba.config(bg="#fed6b8"))
    # =========================================================================
    root3.mainloop()
